package main

import (
	"fmt"
	"net/http"

	"strconv"

	"os"

	"github.com/lijianying10/log"
	"gopkg.in/redis.v3"
)

var RClient *redis.Client

func Get(w http.ResponseWriter, r *http.Request) {
	fmt.Println("兄弟我要资源:", r.RequestURI)
	v, err := RedisGet(RClient, r.RequestURI[1:]).Result()
	if err != nil {
		if err.Error() == "redis: nil" {
			w.WriteHeader(http.StatusNotFound)
			w.Write([]byte("404 page not found"))
			return
		}
		log.Error("出错啦兄弟:", err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("500 internal server error"))
		return
	}
	if len(v) <= 4 {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("500 internal server error,兄弟你的Redis配置错了,前三位是状态码后面是body"))
		return
	}
	i, err := strconv.Atoi(v[:3])
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("500 internal server error,兄弟其实你Redis值给错了,前三位得能转换成INT" + err.Error()))
		return
	}
	w.WriteHeader(i)
	w.Write([]byte(v[3:]))
}

func RedisGet(client *redis.Client, key string) *redis.StringCmd {
	cmd := redis.NewStringCmd("GET", key)
	client.Process(cmd)
	return cmd
}

func main() {
	RClient = redis.NewClient(&redis.Options{
		Addr:     os.Getenv("REDIS"),
		Password: "", // no password set
		DB:       0,  // use default DB
	})

	pong, err := RClient.Ping().Result()
	fmt.Println(pong, err)

	if err != nil {
		log.Fatal("Redis服务器连接不上啊兄弟!")
	}
	fmt.Println("兄弟Redis连接成功了,管理后台你自己看着办吧")
	fmt.Println("大兄弟HTTPServer启动了")
	http.HandleFunc("/", Get)
	log.Fatal(http.ListenAndServe(os.Getenv("LISTEN"), nil))
}
